#!/usr/bin/perl

######################################################################
package Swignition::GenericParser::RoleAttr;
######################################################################

use Swignition::MagicString;
use Swignition::GenericParser::Utils;
use XML::LibXML qw(:all);

sub is_enabled
{
	return 1;
}

sub consume
{
	my $this = shift;
	my $myurl = $this->uri;
	
	# Parse @role
	foreach my $e ($this->{DOM}->getElementsByTagName('*'))
	{
		next unless (length $e->getAttribute('role'));
	
		# Subject: This page
		my $SubjectThisPage = Swignition::RDFModel::Subject->new($myurl);

		# Object: This element
		my $objuri;
		if (length $e->getAttribute('id'))
		{
			$objuri = $myurl . '#' . $e->getAttribute('id');
		}
		else
		{
			$objuri = Swignition::GenericParser::Utils::BNodeURI($e);
		}

		# Predicate: role
		my $role = $e->getAttribute('role');
		$role =~ s/(^\s+|\s+$)//g;
		$role =~ s/\s+/ /g;
		my @role = split / /, $role;
		
		foreach my $r (@role)
		{
			my $nsrole = reservedWordOrCurie($this, $r, $e);			
			my $val    = Swignition::RDFModel::Value->new($objuri, 1);
			$val->setDom($e);
			$SubjectThisPage->addVal($nsrole, $val);
		}		
		
		$this->mergeSubject($SubjectThisPage);
	}
}


sub reservedWordOrCurie
{
	my $page  = shift;
	my $str   = shift;
	my $dom   = shift;
	my $xpath = $dom->getAttribute('_xpath') if ($dom);
	my $safe  = 0;
	
	# Horrible syntax for weirdo blank node.
	if ($str eq '_:' || $str eq '[_:]')
	{
		return 'bnode:///iHateThisSyntax';
	}
	
	# Predefined roles from the XHTML vocab namespace
	if ($str =~ /^\:?( banner | contentinfo | definition | main | navigation
				| note | search | secondary | seealso )$/ix)
	{
		$str = lc("[xhv:$1]");
	}

	# Cope with safe CURIEs.
	if ($str =~ /^\[(.*)\]$/)
	{
		$str  = $1;
		$safe = 1;
	}
	
	# If the string matches CURIE syntax, then resolve the CURIE.
	if ($str =~ /^([a-z_][^\s\:]*)\:(.*)$/i)
	{
		my $pfx = $1;
		my $sfx = $2;
		my $ns  = Swignition::Namespace::bestMatch($pfx, $xpath, @{$page->{Namespaces}});
		
		return $page->uri( $ns->{uri} . $sfx )
			if ($ns);
			
		return 'http://invalid.invalid/ns#'.$sfx
			if ($safe);
	}
	
	# If it wasn't a safe CURIE, then fall back to a URI.
	if (!$safe)
	{
		return $page->uri($str, {'require-absolute'=>1,'element'=>$dom});
	}
	
	return undef;
}


1;
